#!/usr/bin/python
# -*- coding: UTF-8 -*-
import requests
import os


def download_img(content, path):
    index = path.rindex("/")
    folder = path[:index]
    if not os.path.exists(folder):
        os.mkdir(folder)

    with open(path, 'wb') as f:
        f.write(content)


if __name__ == '__main__':
    # 167
    url = "http://lcjq.img.qiaomeigift.com/9c{page}/"
    rootPath = "G:/qiaomeigift"
    i = 1
    while True:
        groupUrl = url.format(page=str(i)) + "{num}.jpg"
        j = 1
        imgSize = 0
        print("正在下载9c{page}组图片".format(page=str(i)))
        while True:
            imgUrl = groupUrl.format(num=str(j))
            img = requests.get(imgUrl)
            img.encoding = "UTF-8"
            if img.text != '您要找的资源已被删除、已更名或暂时不可用。':
                download_img(img.content, '{rootPath}/9c{page}/{num}.jpg'.format(rootPath=rootPath, page=str(i), num=str(j)))
                imgSize = imgSize + 1
            else:
                break
            j = j + 1

        print("已下载完成9c{page}组图片, 图片数据为{imgSize}张".format(page=str(i), imgSize=str(imgSize)))
        if imgSize == 0:
            break

        i = i + 1
